import os
import json

import openpyxl
from openpyxl import Workbook

from entity.position import Position


def save_history(message: str, file_path: str):
    dir_path = os.path.dirname(file_path)
    if dir_path:
        os.makedirs(dir_path, exist_ok=True)
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(message)


def save_resolve_result(data: dict, file_path: str, bank_name: str, bank_name_list: list, status_dict: dict,
                        status_dict_file_path: str):
    # 若状态字典无值，那么说明是当日首次询价
    if not status_dict:
        # 初始化状态字典
        # 获取币种
        resolve_ratio_dict = data[bank_name]
        currency_list = list(resolve_ratio_dict.keys())
        for bank in bank_name_list:
            status_dict[bank] = dict()
            for currency in currency_list:
                status_dict[bank][currency] = dict()
        wb = Workbook()
        ws = wb.active
        row_index = 1
        col_index = 1
        # 保存存款行在excel的列索引
        bank_name_col_dict = dict()
        for currency in currency_list:
            ws.cell(row=row_index, column=col_index, value=currency)
            row_index = row_index + 1
            ws.cell(row=row_index, column=col_index, value='Tensor')
            col_index = col_index + 1
            for header in bank_name_list:
                ws.cell(row=row_index, column=col_index, value=header)
                bank_name_col_dict[header] = col_index
                col_index = col_index + 1
            col_index = 1
            row_index = row_index + 1
            for duration, ratio in resolve_ratio_dict[currency].items():
                # 更新状态字典坐标
                for bank in bank_name_list:
                    status_dict[bank][currency][duration] = {'row': row_index, 'col': bank_name_col_dict[bank]}
                ws.cell(row=row_index, column=col_index, value=duration)
                if ratio != 0:
                    ws.cell(row=row_index, column=bank_name_col_dict[bank_name], value=ratio)
                row_index = row_index + 1
            # 再空一行处理下个币种
            row_index = row_index + 1
        save_to_json(status_dict, status_dict_file_path)
        dir_path = os.path.dirname(file_path)
        if dir_path:
            os.makedirs(dir_path, exist_ok=True)
        wb.save(file_path)
    else:
        # 更新数据(1、老币种+老期限->修改，2、老币种+新期限->不支持[在大模型输出结果中就无这种对应关系]，3、新币种+新、老期限->不追加[在大模型输出结果中就无这种对应关系])
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        resolve_ratio_dict = data[bank_name]
        for currency, ratio_pair in resolve_ratio_dict.items():
            for duration, ratio in ratio_pair.items():
                if ratio == 0:
                    continue
                ws.cell(row=status_dict[bank_name][currency][duration]['row'],
                        column=status_dict[bank_name][currency][duration]['col'], value=ratio)
        wb.save(file_path)


def default_parse_position_instance(obj):
    if isinstance(obj, Position):
        return {'row': obj.row, 'col': obj.col}
    raise TypeError(f'Object of type {obj.__class__.__name__} is not JSON serializable')


def save_to_json(data: dict, file_path: str):
    dir_path = os.path.dirname(file_path)
    if dir_path:
        os.makedirs(dir_path, exist_ok=True)
    with open(file_path, 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, ensure_ascii=False, indent=4)


def parse_json_to_dict(file_path) -> dict:
    if not os.path.exists(file_path):
        dir_path = os.path.dirname(file_path)
        if dir_path:
            os.makedirs(dir_path, exist_ok=True)
        with open(file_path, 'w', encoding='utf-8') as json_file:
            data = {}
            json.dump(data, json_file, ensure_ascii=False, indent=4)
    with open(file_path, 'r', encoding='utf-8') as json_file:
        return json.load(json_file)


if __name__ == '__main__':
    # wb = Workbook()
    # file_path = 'excel.xlsx'
    # dir_path = os.path.dirname(file_path)
    # if dir_path:
    #     os.makedirs(dir_path, exist_ok=True)
    # wb.save(file_path)
    dict1 = parse_json_to_dict('../dict1.json')
    if not dict1:
        print(f"词典无值")
        print(f"{dict1}")
